var NfcAdapter;
var NdefRecord;
var NdefMessage;

function listenNFCStatus() {
	try {
		var main = plus.android.runtimeMainActivity();
		var Intent = plus.android.importClass('android.content.Intent');
		var Activity = plus.android.importClass('android.app.Activity');
		var PendingIntent = plus.android.importClass('android.app.PendingIntent');
		var IntentFilter = plus.android.importClass('android.content.IntentFilter');
		NfcAdapter = plus.android.importClass('android.nfc.NfcAdapter');
		var nfcAdapter = NfcAdapter.getDefaultAdapter(main);
		var intent = new Intent(main, main.getClass());
		intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
		var pendingIntent = PendingIntent.getActivity(main, 0, intent, 0);
		var ndef = new IntentFilter("android.nfc.action.TECH_DISCOVERED");
		ndef.addDataType("*/*");
		var intentFiltersArray = [ndef];
		var techListsArray = [
			["android.nfc.tech.IsoDep"],
			["android.nfc.tech.NfcA"],
			["android.nfc.tech.NfcB"],
			["android.nfc.tech.NfcF"],
			["android.nfc.tech.Nfcf"],
			["android.nfc.tech.NfcV"],
			["android.nfc.tech.NdefFormatable"],
			["android.nfc.tech.MifareClassi"],
			["android.nfc.tech.MifareUltralight"]
		];
		plus.globalEvent.addEventListener("newintent",
			function() {
				console.error('newintent');
				setTimeout(handle_nfc_data1, 1000);
			}, false);
		plus.globalEvent.addEventListener("pause", function(e) {
			if (nfcAdapter) {
				nfcAdapter.disableForegroundDispatch(main);
				console.log('pause');
			}
		}, false);
		plus.globalEvent.addEventListener("resume", function(e) {
			if (nfcAdapter) {
				console.log('resume');
				nfcAdapter.enableForegroundDispatch(main, pendingIntent, intentFiltersArray, techListsArray);
			}
		}, false);
		nfcAdapter.enableForegroundDispatch(main, pendingIntent, intentFiltersArray, techListsArray);
	} catch (e) {
		console.error(e);
	}
}

function handle_nfc_data1() {
	NdefRecord = plus.android.importClass("android.nfc.NdefRecord");
	NdefMessage = plus.android.importClass("android.nfc.NdefMessage");
	var main = plus.android.runtimeMainActivity();
	var intent = main.getIntent();
	console.log("action type:" + intent.getAction());
	if ("android.nfc.action.TECH_DISCOVERED" == intent.getAction()) {
		if (readyWriteData) {
			__write(intent);
			readyWriteData = false;
		} else if (readyRead) {
			__read(intent);
			// readyRead = false;
		}
	}
}

function showToast(msg) {
	uni.showToast({
		title: msg,
		icon: 'none'
	})
}

function __write(intent) {
	try {
		var text = document.getElementById('text').value;
		console.log("text=" + text);
		var textBytes = plus.android.invoke(text, "getBytes");
		// image/jpeg text/plain  
		var textRecord = new NdefRecord(NdefRecord.TNF_MIME_MEDIA,
			plus.android.invoke("text/plain", "getBytes"), plus.android.invoke("", "getBytes"), textBytes);
		var message = new NdefMessage([textRecord]);
		var Ndef = plus.android.importClass('android.nfc.tech.Ndef');
		var NdefFormatable = plus.android.importClass('android.nfc.tech.NdefFormatable');
		var tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
		var ndef = Ndef.get(tag);
		if (ndef != null) {
			var size = message.toByteArray().length;
			console.log("size=" + size);
			ndef.connect();
			if (!ndef.isWritable()) {
				showToast("tag不允许写入");
				return;
			}
			if (ndef.getMaxSize() < size) {
				showToast("文件大小超出容量");
				return;
			}

			ndef.writeNdefMessage(message);
			showToast("写入数据成功.");
			return;
		} else {
			var format = NdefFormatable.get(tag);
			if (format != null) {
				try {
					format.connect();
					format.format(message);
					showToast("格式化tag并且写入message");
					return;
				} catch (e) {
					showToast("格式化tag失败.");
					return;
				}
			} else {
				showToast("Tag不支持NDEF");
				return;
			}
		}
	} catch (e) {
		console.log("error=" + e);
	}

}

function __read(intent) {
	var Parcelable = plus.android.importClass("android.os.Parcelable");
	var rawmsgs = intent.getParcelableArrayExtra("android.nfc.extra.NDEF_MESSAGES");
	var records = rawmsgs[0].getRecords();
	var result = records[0].getPayload();
	var s = plus.android.newObject("java.lang.String", result);
	// console.log('s',s)
	uni.$emit('nfcRead',s)
	
	// document.getElementById('content').textContent = s;
}
// document.addEventListener('plusready', listenNFCStatus, false);

var readyWriteData = false;
var readyRead = false;

function writeData() {
	var textEle = '';
	if (!textEle) {
		return;
	}
	console.log('xiexiexiexiexiexie');
	readyWriteData = true;
	// showToast("请将鞋子靠近手机！");
}

function readData() {
	readyRead = true;
	// showToast("请将鞋子靠近手机！");
}
module.exports = {
	listenNFCStatus,
	writeData,
	readData,
};